import {EventEmitter, OnInit, Output} from '@angular/core';
import {BaseComponent} from './BaseComponent';

import * as moment from 'moment';

export abstract class BaseGrid extends BaseComponent implements OnInit {
  @Output() onEdit = new EventEmitter<{ entity: object }>();
  @Output() onRemove = new EventEmitter<{ entity: object }>();

  _allChecked = false;
  _checkedNumber = 0;
  _dataSet = [];
  _indeterminate = false;

  _pageIndex = 1;
  _pageSize = 10;
  _total = 1;
  _loading = false;
  _sortValue = null;

  params = {};

  constructor() {
    super();
  }

  ngOnInit() {

  }

  setParams(params: any): void {
    this.params = params;
  }

  /**
   * 根据params获取页面展示数据
   * @param params
   */
  abstract queryData(params);

  /**
   * 刷新表格数据
   */
  async flushData() {
    const params = this.params;
    // const params = this.getParams();
    const newParams = {pageIndex: this._pageIndex, pageSize: this._pageSize};
    // 将提交的值中undefined/null去掉
    for (const key in params) {
      if (params[key] !== undefined && params[key] !== null) {
        // 对于js的日期类型, 要转换成字符串再传给后端
        if (params[key] instanceof Date) {
          // newParams[key] = params[key].format('yyyy-MM-dd HH:mm:ss');
          newParams[key] = params[key];
        } else if (moment.isMoment(params[key])) { // 处理moment对象
          newParams[key] = params[key].format('YYYY-MM-DD HH:mm:ss');
        } else {
          newParams[key] = params[key];
        }
      }
    }
    this._loading = true;
    const result = await this.queryData(newParams);
    if (result.success) {
      this._loading = false;
      this._dataSet = result.data.result;
      this._total = result.data.total;
    }
  }

  getSelections() {
    return this._dataSet.filter(value => value.checked);
  }

  addNew(entity) {
    this._dataSet.push(entity);
  }

  _pageIndexChange() {
    this.flushData();
  }

  _pageSizeChang() {
    this._pageIndex = 1;
    this.flushData();
  }

  _checkChange() {
    const allChecked = this._dataSet.every(value => value.checked === true);
    const allUnChecked = this._dataSet.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
  }

  _checkAll(checked) {
    if (checked) {
      this._dataSet.forEach(data => data.checked = true);
    } else {
      this._dataSet.forEach(data => data.checked = false);
    }
    this._checkChange();
  }

}
